/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import domain.Consumption;
import domain.Contract;
import domain.Invoice;
import domain.Mobileconsumption;
import domain.Mobilecontract;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import planner.Operations;
import util.Date;

/**
 *
 * @author Alberto
 */
public class SubirFacturaMovil extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String url = "d:\\";
            Date from = null;
            Date to = null;
            Double amount = 0d;
            Integer idContract = 0;
            DiskFileUpload fu = new DiskFileUpload();
            List list = fu.parseRequest(request);
            Iterator it = list.iterator();
            while (it.hasNext()) {
                FileItem fi = (FileItem) it.next();
                if (!fi.isFormField()) {
                    url += fi.getName();
                    File file = new File(url);
                    fi.write(file);
                } else if (fi.getFieldName().equals("from")) {
                    from = this.creaFecha(fi.getString(), request, response);
                } else if (fi.getFieldName().equals("to")) {
                    to = this.creaFecha(fi.getString(), request, response);
                } else if (fi.getFieldName().equals("amount")) {
                    amount = Double.parseDouble(fi.getString());
                } else if (fi.getFieldName().equals("mobile")) {
                    idContract = Integer.parseInt(fi.getString());
                }
            }

            Mobilecontract mCont = new Operations().getMobileContract(idContract);
            Contract cont = mCont.getContract();
            java.sql.Date fromDate = new java.sql.Date(from.getYear()-1900, from.getMonth()-1, from.getDay());
            int sss = fromDate.getYear();
            java.sql.Date toDate = new java.sql.Date(to.getYear()-1900, to.getMonth()-1, to.getDay());
            java.sql.Date dateSystem = new java.sql.Date(new java.util.Date().getTime());
            Consumption c = new Consumption(cont, amount);
            Invoice i = new Invoice(cont.getBankaccount(), cont.getMobilecontracts().iterator().next().getCompany(), dateSystem, amount);
            Mobileconsumption mc = new Mobileconsumption(i, c, fromDate, toDate, url);
            new Operations().newConsumption(c);
            new Operations().newInvoice(i);
            new Operations().newMobileConsumption(mc);

            RequestDispatcher d = request.getRequestDispatcher("telefonia.jsp");
            d.forward(request, response);

        }catch (Exception e){
            out.print("error");
        }
            
        
    }

    public Date creaFecha(String o, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Date date = null;
        if (o.substring(2, 3).equals("/") && o.substring(5, 6).equals("/")) {
            try {
                int day = Integer.parseInt(o.substring(0, 2));
                int month = Integer.parseInt(o.substring(3, 5));
                int year = Integer.parseInt(o.substring(6, 10));
                date = new Date(year, month, day);
            } catch (Exception e) {
                RequestDispatcher rd = request.getRequestDispatcher("./facturaMovil.jsp?error=true");
                rd.forward(request, response);
            }
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("./facturaMovil.jsp?error=true");
            rd.forward(request, response);
        }

        return date;
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(SubirFacturaMovil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(SubirFacturaMovil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(SubirFacturaMovil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(SubirFacturaMovil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
